#include <controller/UserController.h>
#include <cppwinks/utility/json/Json.h>
#include <dao/UserDao.h>
#include <cppwinks/mysql/exception/SQLException.h>
#include <iostream>

using namespace std;
using namespace json;
using namespace network;

HttpReply UserController::userRegistered(const HttpRequest &req)
{
    try
    {
        Json reqBodyJson;
        reqBodyJson = Json::parseJson(req.getBody());
        string name = reqBodyJson["username"];
        string password = reqBodyJson["password"];
        string gender = reqBodyJson["gender"];
        string phone = reqBodyJson["phone"];
        bool result = true;
        result = user_dao->insertUser(name, password, phone, gender);
        Json ret;
        HttpReply rep("200");
        if (result == true)
        {
            ret["code"] = 1;
            ret["msg"] = "注册成功";
            ret["data"] = "";
        }
        else
        {
            ret["code"] = 0;
            ret["msg"] = "注册失败";
        }

        rep.setBody(ret.toString());
        return rep;
    }
    catch (const mysql::SQLException &e)
    {
        Json ret;
        ret["code"] = 0;
        ret["msg"] = e.what();
        HttpReply rep("400");
        rep.setBody(ret.toString());
        return rep;
    }
    catch (const std::exception &e)
    {
        Json ret;
        ret["code"] = 0;
        ret["msg"] = "请求体JSON解析错误";
        HttpReply rep("400");
        rep.setBody(ret.toString());
        return rep;
    }
}

HttpReply UserController::userLogin(const HttpRequest &req)
{
    Json reqBodyJson;
    try
    {
        reqBodyJson = Json::parseJson(req.getBody());
        string username = reqBodyJson["name"];
        string password = reqBodyJson["password"];
        int stml = user_dao->validateLogin(username, password);
        Json ret;
        if (stml >= 1)
        {
            ret["code"] = 1;
            ret["msg"] = "登录成功";
            ret["data"] = stml;
        }
        else
        {
            ret["code"] = 0;
            ret["msg"] = "用户名或密码错误";
        }
        HttpReply rep("200");
        rep.setBody(ret.toString());
        return rep;
    }
    catch (const mysql::SQLException &e)
    {
        cout << e.what() << endl;
        Json ret;
        ret["code"] = 0;
        ret["msg"] = e.what();
        HttpReply rep("400");
        rep.setBody(ret.toString());
        return rep;
    }
    catch (const std::exception &e)
    {
        cout << e.what() << endl;
        Json ret;
        ret["code"] = 0;
        ret["msg"] = "请求体JSON解析错误";
        HttpReply rep("400");
        rep.setBody(ret.toString());
        return rep;
    }
}
